<template>
    <el-table
        id="inplans-table-inplans"
        ref="tableRef"
        :data="tableData"
        v-bind="tableDefaultAttribute"
        row-key="id"
        :max-height="tableHeight"
        table-layout="auto"
        @sort-change="handleSortChange"
    >
        <template #empty>
            <span>无数据</span>
        </template>
        <el-table-column type="selection" width="55" :align="'center'" />
        <template v-for="col in tableColumns" :key="col.prop">
            <el-table-column
                v-if="!col.isHidden"
                :align="col.align"
                :prop="col.prop"
                :label="col.label"
                :formatter="col.formatter"
                :type="col.type"
                :fixed="col.fixed"
                :width="col.width"
            >
            </el-table-column>
        </template>
    </el-table>
    <el-button-group class="bg">
        <el-space>
            <el-button
                class="btn"
                type="primary"
                :icon="Delete"
                @click="onDelete"
                >删除</el-button
            >
            <el-button
                class="btn"
                type="primary"
                :icon="Search"
                @click="onQuery"
                >查询</el-button
            >
            <el-button
                class="btn"
                type="primary"
                :icon="Refresh"
                @click="onRefresh"
                >刷新</el-button
            >
        </el-space>
    </el-button-group>
    <div class="page">
        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[50, 100, 150, 200]"
            layout="sizes, prev, pager, next, total"
            :total="totalnum"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
    </div>
    <el-dialog
        v-model="dialogQueryVisible"
        title="箱动态查询"
        draggable
        destroy-on-close
    >
        <QueryForm
            :queryItems="queryItems"
            :tableID="tableRef!.$el.id"
            @yh-closedialog="onCloseDialog"
        ></QueryForm>
    </el-dialog>
</template>
<script setup lang="ts" name="PortCntrStat">
import { ref, reactive, onMounted } from 'vue';
import { storeToRefs } from 'pinia';
import { isEmpty } from 'lodash';
import type { TableInstance } from 'element-plus';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Delete, Search, Refresh } from '@element-plus/icons-vue';
import { useAppStore } from '@/store/app';
import {
    transFormatter, formatDateTime,
    pickQueryFromTable
} from '@/common/tools';
import {
    tableDefaultAttribute,
    useTableInfo,
    tableColumnDefault,
} from '@/hooks/useTable';
import type { QueryItem, TableColumn } from '@/common/types/app';
import type { PortCntrStatModel } from '@/common/types/container';
import { Request } from '@/app/request';
import { tableMaxHeightAdjust } from '@/common/const';
const tableRef = ref<TableInstance>();
const tableData = ref<Array<PortCntrStatModel>>([]);
const { cntrStat, cyCfs, cntrStatus } = storeToRefs(useAppStore());
const tableHeight = ref(600);
const dialogQueryVisible = ref(false);

const onFormatter = (_row: any, column: any, cellValue: any) => {
    let data: { value: string | number; label: string }[];
    if (column['property'] === 'cntr_stat_cod') {
        data = cntrStat.value;
    } else if (column['property'] === 'current_stat') {
        data = cntrStatus.value;
    } else if (column['property'] === 'cfs_cod') {
        data = cyCfs.value;
    } else {
        return cellValue;
    }

    return transFormatter(cellValue, data);
};
const tableColumns = reactive<TableColumn[]>([
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'cntr',
        label: '箱号',
        fixed: 'left',
        sortable: 'custom',
        formFieldItemType: 'input',
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'cntr_stat_cod',
        label: '箱动态',
        sortable: 'custom',
        fixed: 'left',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrStat.value,
        width: 150,
    },
    {
        ...tableColumnDefault,
        order: 10,
        prop: 'stat_tim',
        fixed: 'left',
        label: '动态时间',
        sortable: 'custom',
        formatter: formatDateTime,
        formFieldItemType: 'datetime',
        width: 250,
    },
    {
        ...tableColumnDefault,
        order: 2,
        prop: 'current_stat',
        label: '箱状态',
        sortable: 'custom',
        fixed: 'left',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cntrStatus.value,
        width: 90,
    },
    {
        ...tableColumnDefault,
        order: 10,
        prop: 'cfs_cod',
        label: '站点',
        sortable: 'custom',
        formatter: onFormatter,
        formFieldItemType: 'single',
        optionalValues: cyCfs.value,
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 1,
        prop: 'plan_id',
        label: '计划号',
        formFieldItemType: 'input',
        width: 80,
    },

    {
        ...tableColumnDefault,
        order: 11,
        prop: 'bill_no',
        label: '提单号',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'dam_id',
        label: '箱况',
        sortable: 'custom',
        width: 120,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'truck_no',
        label: '车号',
        sortable: 'custom',
        width: 200,
    },
    {
        ...tableColumnDefault,
        order: 11,
        prop: 'driver_tel',
        label: '电话',
        sortable: 'custom',
        width: 200,
    },
]);
const queryItems: Array<QueryItem> = pickQueryFromTable(tableColumns);
onMounted(() => {
    tableHeight.value = window.innerHeight - tableMaxHeightAdjust;
});
let queryWhere = {};

const onRefresh = async () => {
    const req = new Request('箱动态查询', {
        skip: (currentPage.value - 1) * pageSize.value,
        take: pageSize.value,
        order: orders,
        ...queryWhere,
    });
    const r = await req.post();

    totalnum.value = r.ext;
    tableData.value.length = 0;

    if (!isEmpty(r.obj)) {
        tableData.value = r.obj;
    }
    // console.log(cntrStat);
    
};
const {
    currentPage,
    orders,
    pageSize,
    totalnum,
    handleSizeChange,
    handleCurrentChange,
    handleSortChange,
} = useTableInfo(onRefresh);
const onCloseDialog = async (arg: any) => {
    if (dialogQueryVisible.value) {
        // 查询
        currentPage.value = 1;
        queryWhere = arg;
        onRefresh();

        dialogQueryVisible.value = false;
    }
};
const onDelete = async () => {
    const rows: Array<PortCntrStatModel> = tableRef.value?.getSelectionRows() || [];
    if (rows.length <= 0) {
        ElMessage.info({
            message: '请选择要删除动态',
        });
        return;
    }

    // const delids = ids.join(',');
    const cr = await ElMessageBox.confirm('', '确认删除选中的动态', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(() => {
            return true;
        })
        .catch(() => {
            return false;
        });
    if (cr) {
        //
        const stats = [];
        for (let index = 0; index < rows.length; index++) {
            const element = rows[index];
            stats.push({ id: element.id, cntr_no: element.cntr_no });
        }
        const req = new Request('箱动态删除', { cntrStats: stats });
        const r = await req.post();
        if (r.code > 100) {
            stats.forEach((element) => {
                const f_index = tableData.value.findLastIndex((row) => row.id === element.id);
                if (f_index > -1) {
                    tableData.value.splice(f_index, 1);
                }
            });
        }
    }
};
const onQuery = () => {
    dialogQueryVisible.value = true;
};
/*
 * @Description:
 * @Author: zht
 * @Date: 2024-08-22
 * @LastEditTime: 2024-08-22
 * @LastEditors: zht
 * 佛祖保佑      永无BUG
 */
</script>
<style lang="scss" scoped>
.bg {
    margin-top: 10px;

    .btn {
        margin-right: 10px;
    }
}

.page {
    float: right;
    margin-top: 10px;
}</style>
